﻿/*
 * Created by SharpDevelop.
 * User: IEscarro
 * Date: 9/3/2009
 * Time: 2:56 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
using Buaya.Model;

namespace Buaya.Gui
{
	/// <summary>
	/// Description of TimesheetForm.
	/// </summary>
	public partial class TimesheetForm : BaseForm
	{
		public TimesheetForm() : this(new List<Timesheet>())
		{
			
		}
		
		public TimesheetForm(IList<Timesheet> t)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			listView1.Resize += delegate { columnHeader1.Width = listView1.Width - 22 - (columnHeader2.Width + columnHeader3.Width); };
			Model = t;
		}
		
		protected override void OnModelChanged(EventArgs e)
		{
			base.OnModelChanged(e);
			TimesheetAdded += delegate { RefreshList(); };
			RefreshList();
		}
		
		void RefreshList()
		{
			listView1.Items.Clear();
			foreach (Timesheet t in Model as IList<Timesheet>) {
				ListViewItem li = listView1.Items.Add(t.Employee.Name.ToString());
				li.SubItems.Add(t.Date.ToString("d/M/yyyy HH:mm:ss"));
				li.SubItems.Add(t.In ? "IN" : "OUT");
			}
		}
		
		void NewToolStripMenuItemClick(object sender, EventArgs e)
		{
			using (TimesheetEmployeeForm f = new TimesheetEmployeeForm()) {
				if (MainForm.Instance.AddDialog(f) == DialogResult.OK) {
					AddTimesheet(f.Model as Timesheet);
				}
			}
		}
		
		public virtual void AddTimesheet(Timesheet t)
		{
			(Model as IList<Timesheet>).Add(t);
			OnTimesheetAdded(null);
		}
		
		protected virtual void OnTimesheetAdded(EventArgs e)
		{
			if (TimesheetAdded != null) {
				TimesheetAdded(this, e);
			}
		}
		
		public virtual event EventHandler TimesheetAdded;
		
		void ButtonSaveAndCloseClick(object sender, EventArgs e)
		{
			Save();
			Close();
		}
		
		void Save()
		{
			foreach (Timesheet t in Model as IList<Timesheet>) {
				SessionFacade.SaveOrUpdateTimesheet(t);
			}
		}
		
		void ButtonSaveAndClearClick(object sender, EventArgs e)
		{
			Save();
			ButtonClearClick(sender, e);
		}
		
		void ButtonClearClick(object sender, EventArgs e)
		{
			Model = new List<Timesheet>();
		}
	}
}
